# -*- coding: utf-8 -*-
import json
import logging

from django.views.decorators.http import require_GET, require_POST
from future.utils import raise_with_traceback

from api.notification import handler
from common.cache import redis_cache
from common.notification import db as db
from common.notification.db import get_last_in_app_announcement
from common.notification.model import NOTIFY_TYPE, NOTIFY_ICONS
from common.utils.api import token_required
from common.utils.decorator import response_wrapper
from common.utils.exceptions import ParamError
from common.utils.tz import now_ts

_LOGGER = logging.getLogger(__name__)


@require_GET
@response_wrapper
def get_notifications_category(request):
    """
    消息分类列表
    """
    user_id = request.user_id
    _list = []
    for value in NOTIFY_TYPE.values():
        unread = redis_cache.get_unread_notify_count(user_id, value) if value in (
            NOTIFY_TYPE.AWARD, NOTIFY_TYPE.CAMPAIGN) else 0
        last_msg = db.get_lasted_notification(user_id, value)
        last_msg = handler.create_last_msg_lite(last_msg, u"暂无消息")
        _list.append({
            "type": value,
            "name": NOTIFY_TYPE.get_label(value),
            "icon": NOTIFY_ICONS[value],
            "unread": unread,
            "last_msg": last_msg
        })
    _list.sort(key=lambda x: x['type'])
    return {'list': _list}


@require_POST
@token_required
@response_wrapper
def read(request):
    try:
        data = json.loads(request.body)
        notify_id = int(data['notify_id'])
    except Exception as e:
        raise_with_traceback(ParamError(e))
    user_id = request.user_id
    notify_type = db.read_notify(user_id, notify_id)
    if notify_type is not None:
        redis_cache.decrease_unread_notify_count(user_id, notify_type)
    return {}


@require_GET
@response_wrapper
def get_notifications(req, notify_type):
    try:
        page = int(req.GET.get('page', 0))
        size = int(req.GET.get('size', 0))
        notify_type = int(notify_type)
    except Exception as e:
        raise_with_traceback(ParamError(e))
    _list = handler.view_notifications(int(req.user_id), notify_type, page, size)
    data = {
        'list': _list,
        'page': page if page > 0 else 1,
        'size': len(_list)
    }
    return data


@require_GET
@response_wrapper
def get_notification_detail(requset, notify_id):
    """
    单个消息详情
    """
    notify_id = int(notify_id)
    data = handler.view_single_notification(requset.user_id, notify_id)
    return data


@require_GET
@response_wrapper
def unread_count(request):
    """
    获取总的个人消息未读数量
    """
    user_id = request.user_id
    if not user_id:
        return {'count': 0}
    count = handler.get_unread_count(user_id)
    return {"count": count}


@require_GET
@response_wrapper
def get_in_app_announcement(request):
    item = get_last_in_app_announcement(now_ts())
    if item:
        return item.as_dict()
    else:
        return {}
